package cn.xfdzx.android.apps.shop.util;

import android.app.Activity;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.tabs.TabLayout;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.xfdzx.android.apps.shop.R;

public class Utils {

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 300;
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }
    /**
     * 判断数据网络是否开启
     *
     * @param context
     * @return
     */
    public static boolean haveIntent(Context context) {
        boolean mobileDataEnabled = false; // Assume disabled
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        try {
            Class cmClass = Class.forName(cm.getClass().getName());
            Method method = cmClass.getDeclaredMethod("getMobileDataEnabled");
            method.setAccessible(true); // Make the method callable
            // get the setting for "mobile data"
            mobileDataEnabled = (Boolean) method.invoke(cm);
        } catch (Exception e) {
            // Some problem accessible private API
            // TODO do whatever error handling you want here
        }
        return mobileDataEnabled;
    }

    /**
     * 判断手机号合法性
     *
     * @param phoneNumber 手机号
     * @return
     */
    public static boolean checkPhoneNum(String phoneNumber) {
        String regExp = "^((13[0-9])|(15[^4])|(18[0-9])|(17[0-8])|(14[5-9])|(166)|(19[8,9])|)\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(phoneNumber);
        return m.matches();
    }

    /**
     * 根据手机的分辨率获取窄边值 单位:px
     */
    public static int getMinEdge(Context context) {
        Context appContext = context.getApplicationContext();
        int w = appContext.getResources().getDisplayMetrics().widthPixels;
        int h = appContext.getResources().getDisplayMetrics().heightPixels;
        return Math.min(w, h);
    }

    /**
     * Toast 短通知
     *
     * @param context
     * @param param
     */
    public static void toastMessage(Context context, String param) {
        Toast.makeText(context, param, Toast.LENGTH_SHORT).show();
    }


    public static Dialog addDialog(Context context, int layout_id, int content, int right, View.OnClickListener onClickListener) {
        Dialog dialog = new Dialog(context, R.style.ExitDialog);
        View layout = View.inflate(context, layout_id, null);
        ((TextView) layout.findViewById(R.id.tv_content)).setText(content);
        ((TextView) layout.findViewById(R.id.tvw_dialog_cancel)).setText(R.string.cancel);
        ((TextView) layout.findViewById(R.id.tvw_dialog_determine)).setText(right);
        dialog.setContentView(layout);
        dialog.setCanceledOnTouchOutside(true);
        layout.findViewById(R.id.tvw_dialog_determine).setOnClickListener(onClickListener);
        final Dialog finalDialog = dialog;
        ((TextView) layout.findViewById(R.id.tvw_dialog_cancel)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finalDialog.dismiss();
            }
        });
        return dialog;
    }
    public static Dialog addDialog(Context context, int layout_id, String content, int right, View.OnClickListener onClickListener) {
        Dialog dialog = new Dialog(context, R.style.ExitDialog);
        View layout = View.inflate(context, layout_id, null);
        ((TextView) layout.findViewById(R.id.tv_content)).setText(content);
        ((TextView) layout.findViewById(R.id.tvw_dialog_cancel)).setText(R.string.cancel);
        ((TextView) layout.findViewById(R.id.tvw_dialog_determine)).setText(right);
        dialog.setContentView(layout);
        dialog.setCanceledOnTouchOutside(true);
        layout.findViewById(R.id.tvw_dialog_determine).setOnClickListener(onClickListener);
        final Dialog finalDialog = dialog;
        ((TextView) layout.findViewById(R.id.tvw_dialog_cancel)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finalDialog.dismiss();
            }
        });
        return dialog;
    }

    /**新增设置左右点击监听的dialog*/
    public static Dialog addSubmitDialog(Context context, int layout_id, String content,String left, String right,
                                         View.OnClickListener onLeftClickListener,View.OnClickListener onrightClickListener) {
        Dialog dialog = new Dialog(context, R.style.ExitDialog);
        View layout = View.inflate(context, layout_id, null);
        ((TextView) layout.findViewById(R.id.tv_content)).setText(content);
        ((TextView) layout.findViewById(R.id.tvw_dialog_cancel)).setText(left);
        ((TextView) layout.findViewById(R.id.tvw_dialog_determine)).setText(right);
        dialog.setContentView(layout);
        dialog.setCanceledOnTouchOutside(true);
        layout.findViewById(R.id.tvw_dialog_determine).setOnClickListener(onrightClickListener);
        layout.findViewById(R.id.tvw_dialog_cancel).setOnClickListener(onLeftClickListener);

        return dialog;
    }

    public static Dialog addSureDialog(Context context, int layout_id ) {
        Dialog dialog = new Dialog(context, R.style.ExitDialog);
        View layout = View.inflate(context, layout_id, null);

        dialog.setContentView(layout);
        dialog.setCanceledOnTouchOutside(true);
        final Dialog finalDialog = dialog;
        ((TextView) layout.findViewById(R.id.tv_ok)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finalDialog.dismiss();
            }
        });
        return dialog;
    }
    /**
     * 设置右侧颜色值
     * **/
    public static Dialog addDialog(Context context, int layout_id, int content, int right, View.OnClickListener onClickListener,int coclor) {
        Dialog dialog = new Dialog(context, R.style.ExitDialog);
        View layout = View.inflate(context, layout_id, null);
        ((TextView) layout.findViewById(R.id.tv_content)).setText(content);
        ((TextView) layout.findViewById(R.id.tvw_dialog_cancel)).setText(R.string.cancel);
        ((TextView) layout.findViewById(R.id.tvw_dialog_determine)).setText(right);
        ((TextView) layout.findViewById(R.id.tvw_dialog_determine)).setTextColor(context.getResources().getColor(R.color.color_FB9129));
        dialog.setContentView(layout);
        dialog.setCanceledOnTouchOutside(true);
        layout.findViewById(R.id.tvw_dialog_determine).setOnClickListener(onClickListener);
        final Dialog finalDialog = dialog;
        ((TextView) layout.findViewById(R.id.tvw_dialog_cancel)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finalDialog.dismiss();
            }
        });
        return dialog;
    }


    public static String getMiddleColor(String color1, String color2) {
        if (color1.contains("#") && color2.contains("#") && color1.length() == color2.length() && color2.length() == 7) {
            String tempColor1 = color1.replace("#", "");
            String tempColor2 = color2.replace("#", "");
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("#");
            for (int i = 0; i < tempColor1.length(); i++) {
                String tempResult = (changeHex2Int(String.valueOf(tempColor1.charAt(i)))
                        + changeHex2Int(String.valueOf(tempColor2.charAt(i)))) / 2 + "";
                stringBuffer.append(changeInt2Hex(tempResult));
            }
            return stringBuffer.toString();
        }
        return "";
    }

    private static int changeHex2Int(String temp) {
        BigInteger srch = new BigInteger(temp, 16);
        return Integer.valueOf(srch.toString());
    }

    private static String changeInt2Hex(String temp) {
        BigInteger srch = new BigInteger(temp, 10);
        return Integer.toHexString(Integer.parseInt(srch.toString()));
    }

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public static void callPhone(Activity activity,String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        activity.startActivity(intent);
    }

    /**
     * 时间戳转换成日期格式字符串
     * @param seconds 精确到秒的字符串
     * @return
     */
    public static String timeStamp2Date(String seconds,String format) {
        if(seconds == null || seconds.isEmpty() || seconds.equals("null")){
            return "";
        }
        if(format == null || format.isEmpty()){
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(Long.valueOf(seconds+"000")));
    }

    /**
     * 日期格式字符串转换成时间戳
     * @param format 如：yyyy-MM-dd HH:mm:ss
     * @return 到秒
     */
    public static String date2TimeStamp(String date_str,String format){
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(format);
//            return String.valueOf(sdf.parse(date_str).getTime()/1000);
            return String.valueOf(sdf.parse(date_str).getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 加法运算
     * @param m1
     * @param m2
     * @return
     */
    public static double addDouble(double m1, double m2) {
        BigDecimal p1 = new BigDecimal(Double.toString(m1));
        BigDecimal p2 = new BigDecimal(Double.toString(m2));
        return p1.add(p2).doubleValue();
    }

    /**
     * 减法运算
     * @param m1
     * @param m2
     * @return
     */
    public static double subDouble(double m1, double m2) {
        BigDecimal p1 = new BigDecimal(Double.toString(m1));
        BigDecimal p2 = new BigDecimal(Double.toString(m2));
        return p1.subtract(p2).doubleValue();
    }

    /**
     * 乘法运算
     * @param m1
     * @param m2
     * @return
     */
    public static double mul(double m1, double m2) {
        BigDecimal p1 = new BigDecimal(Double.toString(m1));
        BigDecimal p2 = new BigDecimal(Double.toString(m2));
        return p1.multiply(p2).doubleValue();
    }


    /**
     *  除法运算
     *   @param   m1
     *   @param   m2
     *   @param   scale
     *   @return
     */
    public static double div(double m1, double m2, int scale) {
        if (scale < 0) {
            throw new IllegalArgumentException("Parameter error");
        }
        BigDecimal p1 = new BigDecimal(Double.toString(m1));
        BigDecimal p2 = new BigDecimal(Double.toString(m2));
        return p1.divide(p2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
    }
    /**
     * 复制内容到剪切板
     *
     * @param copyStr
     * @return
     */
    public   static boolean copy(Context context,String copyStr) {
        try {
            //获取剪贴板管理器
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", copyStr);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断点击是否过快
     *
     * @return
     */
    public static boolean isClickQuckily() {
        long now = System.currentTimeMillis();
        if(now - lastClickTime >1000){
            lastClickTime = now;
            return false;
        }
        return true;
    }

    public static String toNumber(int number) {
        String str = "";
        if (number <= 0) {
            str = "0";
        } else if (number < 10000) {
            str = number + "";
        } else {
            double d = (double) number;
            //将数字转换成万
            double num = d / 10000;
            BigDecimal b = new BigDecimal(num);
            //四舍五入保留小数点后一位
            double f1 = b.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue();
            str = f1 + "w";
        }
        return str;
    }

    /*
     * This method was copied from http://stackoverflow.com/a/10028267/694378.
     * The only modifications I've made are to remove a couple of Log
     * statements which could slow things down slightly.
     */
    public static Bitmap fastblur(Bitmap sentBitmap, int radius) {

        Bitmap bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

        return (bitmap);
    }

    public static int dp2px(Context context, float dp) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dp * scale + 0.5f);
    }

    /**tab专用间距*/
    public static void reflexAfterService(final TabLayout tabLayout){
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                    int dp10 = DensityUtils.dip2px(tabLayout.getContext(), 33);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width ;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);
                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
